<template>
  <div class="container" @touchmove.prevent>
    <!-- <div class="language" @click="changeLang">
      <span :class="$i18n.locale == 'en'?'language__alt':'language__active'">中</span>
      <span :class="$i18n.locale == 'en'?'language__active':'language__alt'">E</span>
    </div> -->
    <div class="title">
      <!-- <p class="t1">普世医学</p> -->
      <p class="t1">医学影像</p>
      <p class="t2">智能分析与推荐平台</p>
    </div>
    <div class="field">
      <van-cell-group>
        <van-field
          v-model="username"
          label="用户名"
          :placeholder="$t('login.username_tips')"
        />
        <van-field
          v-model="password"
          type="password"
          :placeholder="$t('login.password_tips')"
          :label="$t('login.password')"
        />
        <van-field
          readonly
          clickable
          label="身份"
          :value="role"
          placeholder="选择您的身份"
          @click="showPicker = true"
        />
        <van-popup v-model="showPicker" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="showPicker = false"
            @confirm="onConfirm"
          />
        </van-popup>
      </van-cell-group>
      <div class="xy">
        <van-checkbox
          @click="radioClick"
          class="groups"
          v-model="radio1"
          shape="square"
          icon-size="0.16rem"
          >记住用户名和密码</van-checkbox
        >
        <!-- <p class="text">记住用户名</p> -->
      </div>
      <div class="xy">
        <van-checkbox
          class="groups"
          v-model="radio"
          shape="square"
          icon-size="0.16rem"
          >我已阅读并同意<span>用户协议</span></van-checkbox
        >
        <!-- <p class="text">我已阅读并同意<span>用户协议</span></p> -->
      </div>
      <van-button
        class="login-btn"
        type="primary"
        color="#4779e7"
        round
        block
        @click="login"
        >登录</van-button
      >
      <van-button
        class="login-btn"
        type="primary"
        round
        block
        @click="touristLogin"
        >游客登录</van-button
      >
      <p class="new" @click="showPopup">注册新账号</p>
      <p class="forget" @click="forgetPassword">忘记密码？</p>
    </div>
    <div class="login-img" v-show="isShow">
      <!-- <img src="@/assets/images/login1.png" alt /> -->
      <van-image
        width="100%"
        height="100%"
        :src="require('@/assets/images/5ba611884a3b8.png')"
      />
    </div>
    <van-overlay :show="show" :z-index="15">
      <div class="wrapper" @click.stop>
        <van-loading color="#1989fa" />
      </div>
      <!-- <van-icon class-prefix="icon" name="duibi" /> -->
    </van-overlay>
    <van-popup v-model="pshow" class="pshow" closeable>
      <van-form @submit="onSubmit">
        <div class="field2">
          <van-cell-group>
            <van-field
              readonly
              clickable
              required
              label="身份"
              :value="roleRe"
              name="reRole"
              placeholder="选择您的身份"
              :rules="[{ required: true, message: '请选择您的身份' }]"
              @click="showPicker2 = true"
            />
            <van-popup v-model="showPicker2" round position="bottom">
              <van-picker
                show-toolbar
                :columns="columns2"
                @cancel="showPicker2 = false"
                @confirm="onConfirm2"
              />
            </van-popup>
            <van-field
              v-model="reUsername"
              name="reUsername"
              required
              :rules="[
                { pattern: pattern, message: '必须且只含有数字或字母，3-10位' },
              ]"
              :label="$t('login.username')"
              :placeholder="$t('login.username_tips')"
            />
            <van-field
              v-model="rePassword"
              required
              name="rePassword"
              type="password"
              :rules="[
                {
                  pattern: pattern2,
                  message: '至少6-16个字符，至少1个小写字母和1个数字',
                },
              ]"
              placeholder="请输入登陆密码"
              label="密码"
            />
            <van-field
              v-model="rePassword2"
              name="rePassword2"
              required
              type="password"
              placeholder="请再次输入登陆密码"
              :rules="[{ validator: validator1, message: '密码不一致' }]"
              label="密码"
            />
            <van-field
              v-model="rePhone"
              name="rePhone"
              required
              :rules="[
                {
                  pattern: pattern3,
                  message: '请输入正确的手机号码',
                },
              ]"
              placeholder="请输入您的手机号码"
              label="手机"
            />
            <van-field
              v-model="reCode"
              name="reCode"
              required
              center
              clearable
              :rules="[{ required: true, message: '请填写验证码' }]"
              label="短信验证码"
              placeholder="请输入短信验证码"
            >
              <template #button>
                <van-button
                  :disabled="codeFlag"
                  @click="checkCode"
                  size="small"
                  type="primary"
                  >{{ codeFlag ? codeTime : "发送验证码" }}</van-button
                >
              </template>
            </van-field>
          </van-cell-group>
          <van-button
            class="login-btn"
            type="primary"
            color="#4779e7"
            round
            block
            >注册</van-button
          >
        </div>
      </van-form>
    </van-popup>
    <van-popup v-model="pwshow" class="pshow" closeable>
      <van-form @submit="onforgetSubmit">
        <div class="field2">
          <van-cell-group
            ><van-field
              v-model="fgPhone"
              name="fgPhone"
              required
              :rules="[
                {
                  pattern: pattern3,
                  message: '请输入正确的手机号码',
                },
              ]"
              placeholder="请输入您的手机号码"
              label="手机"
            />
            <van-field
              v-model="fgCode"
              name="fgCode"
              required
              center
              clearable
              :rules="[{ required: true, message: '请填写验证码' }]"
              label="短信验证码"
              placeholder="请输入短信验证码"
            >
              <template #button>
                <van-button
                  :disabled="forgetcodeFlag"
                  @click="checkForgetCode"
                  size="small"
                  type="primary"
                  >{{
                    forgetcodeFlag ? forgetcodeTime : "发送验证码"
                  }}</van-button
                >
              </template>
            </van-field>
            <van-field
              v-model="fgPassword1"
              required
              name="fgPassword1"
              type="password"
              :rules="[
                {
                  pattern: pattern2,
                  message: '至少6-16个字符，至少1个小写字母和1个数字',
                },
              ]"
              placeholder="请输入重置密码"
              label="密码"
            />
            <van-field
              v-model="fgPassword2"
              name="fgPassword2"
              required
              type="password"
              placeholder="请再次输入重置密码"
              :rules="[{ validator: validator2, message: '密码不一致' }]"
              label="密码"
            />
          </van-cell-group>
          <van-button
            class="login-btn"
            type="primary"
            color="#4779e7"
            round
            block
            >修改</van-button
          >
        </div>
      </van-form>
    </van-popup>
    <!-- <van-popup v-model="roleShow" position="bottom" :style="{ height: '100%' }">
      <div class="role-box">
        <p class="titles">请选择您的身份</p>
        <div class="role">
          <div>
            <img src="@/assets/images/us.png" alt="" />
            <p>用户</p>
          </div>
          <div>
            <img src="@/assets/images/do.png" alt="" />
            <p>医生</p>
          </div>
          <div>
            <img src="@/assets/images/fk.png" alt="" />
            <p>游客</p>
          </div>
        </div>
        <van-button class="role-btn" type="primary" round block
          >确认</van-button
        >
      </div>
    </van-popup> -->
  </div>
</template>

<script>
import { Notify } from "vant";
import { Toast } from "vant";
import {
  setStorage,
  setCookie,
  getCookie,
  delCookie,
  removeStorage,
  getStorage,
} from "@/utils/auth";
import {
  login,
  wxReister,
  wxGetphone,
  wxCheckname,
  appsLogin,
  appsChangePassword,
  wxvcode,
  visLogin,
} from "@/api/home";
export default {
  name: "login",
  components: {},
  data() {
    return {
      username: "",
      password: "",
      originalHeight: 0, //原始高度
      screenHeight: 0, //实时高度
      isShow: true,
      show: false, // 模糊层
      pshow: false,
      reUsername: "",
      rePassword: "",
      rePassword2: "",
      rePhone: "",
      reCode: "",
      pattern: /^[a-zA-Z0-9]{3,10}$/,
      pattern2: /^(?=.*[a-z])(?=.*\d)[^]{6,16}$/,
      pattern3: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/,
      codeFlag: false,
      codeTime: "",
      timer: null,
      pwshow: false,
      fgPhone: "",
      fgCode: "",
      fgPassword1: "",
      fgPassword2: "",
      forgetcodeFlag: false,
      forgetcodeTime: "",
      forgetTimer: null,
      radio: false,
      radio1: false,
      role: "",
      showPicker: false,
      roleIndex: null,
      columns: ["一般用户", "医学专业人士(医生，医学生，科研人员)"],
      columns2: ["一般用户", "医学专业人士(医生，医学生，科研人员)"],
      roleRe: "",
      showPicker2: false,
      roleIndex2: null,
      roleShow: false,
    };
  },
  computed: {},
  watch: {
    screenHeight(newHeight) {
      //监听屏幕高度变化
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isiOS) {
        this.isShow = true;
      } else {
        this.isShow = this.originalHeight <= newHeight;
      }
    },
  },
  methods: {
    // showRole() {
    //   this.roleShow = true;
    // },
    onConfirm(value, index) {
      this.role = value;
      this.roleIndex = index;
      this.showPicker = false;
    },
    onConfirm2(value, index) {
      this.roleRe = value;
      this.roleIndex2 = index;
      this.showPicker2 = false;
    },
    // 登录
    async login() {
      if (this.username === "") {
        Toast.fail(this.$t("login.username_tips"));
      } else if (this.password === "") {
        Toast.fail(this.$t("login.password_tips"));
      } else if (this.roleIndex == null) {
        Toast.fail("请选择您的身份");
      } else if (this.radio == false) {
        Toast.fail("您还未同意用户协议");
      } else {
        let data = {
          name: this.username,
          password: this.password,
          idRoute: this.roleIndex,
        };
        let res = await appsLogin(data);
        if (res.data.status == 200) {
          if (this.radio1) {
            let data = {
              userName: this.username,
              passWord: this.password,
            };
            setCookie("re_username", JSON.stringify(data), 30);
          } else {
            delCookie("re_username");
          }
          this.show = true;
          Toast.success(this.$t("login.login_succeed"));
          if (this.roleIndex == 0) {
            setStorage("userToken", res.data.status);
          } else if (this.roleIndex == 1) {
            setStorage("doctorToken", "doctor");
          } else {
            setStorage("doctorToken", "scientific");
          }
          this.$store.dispatch("user/commitSaveData", res.data.info);
          setStorage("userInfo", JSON.stringify(res.data.info));
          removeStorage("registerFlag");
          window.location.reload();
        } else {
          this.show = false;
          Toast.fail(res.data.msg);
        }
        // }
      }
    },
    // 游客登陆
    touristLogin() {
      if (this.radio == false) {
        Toast.fail("您还未同意用户协议");
      } else {
        visLogin().then((res) => {
          if (res.status.code == 200) {
            this.show = true;
            Toast.success(this.$t("login.login_succeed"));
            this.$store.dispatch("user/commitSaveData", res.data.list);
            setStorage("userInfo", JSON.stringify(res.data.list));
            setStorage("userToken", res.data.status);
            removeStorage("registerFlag");
            window.location.reload();
          }
        });
      }
    },
    watchResize() {
      //实时变化的窗口高度
      this.screenHeight = document.documentElement.clientHeight;
    },
    // 切换语言
    changeLang() {
      let lang = this.$i18n.locale === "cn" ? "en" : "cn";
      setStorage("lang", lang);
      this.$i18n.locale = lang;
      if (lang === "cn") {
        Toast.success("切换成功");
      } else {
        Toast.success("Switchover succeeded");
      }
    },
    showPopup() {
      this.pshow = true;
    },
    validator1(val) {
      if (val != this.rePassword) {
        return false;
      }
    },
    validator2(val) {
      if (val != this.fgPassword1) {
        return false;
      }
    },
    // 验证码
    async checkCode() {
      let code = this.reCode;
      let flag = this.pattern3.test(this.rePhone);
      if (this.rePhone == "" || flag == false) {
        Toast.fail("请输入手机号码");
      } else if (this.roleIndex2 == null) {
        Toast.fail("请选择您的身份");
      } else {
        let res = await wxGetphone(this.rePhone, 5, this.roleIndex2);
        if (res.data.status == "OK") {
          Toast.success(res.data.msg);
          const TIME_COUNT = 60;
          if (!this.timer) {
            this.codeTime = TIME_COUNT;
            this.codeFlag = true;
            this.timer = setInterval(() => {
              if (this.codeTime > 0 && this.codeTime <= TIME_COUNT) {
                this.codeTime--;
              } else {
                this.codeFlag = false;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        } else {
          Toast.fail(res.data.msg);
        }
      }
    },
    //提交注册
    async onSubmit(values) {
      console.log(values, 11);
      let check = await wxCheckname(values.reUsername);
      if (check.data.status != 200) {
        Toast.fail(check.data.msg);
      } else {
        let data = {
          name: values.reUsername,
          password: values.rePassword,
          phone: values.rePhone,
          code: values.reCode,
          idRoute: this.roleIndex2,
        };
        let res = await wxReister(data);
        if (res.data.status == 200) {
          Toast.success("注册成功");
          this.pshow = false;
        } else {
          Toast.fail(res.data.msg);
        }
      }
    },
    // 忘记密码
    forgetPassword() {
      this.pwshow = true;
    },
    // 忘记密码验证码
    async checkForgetCode() {
      let code = this.fgCode;
      let flag = this.pattern3.test(this.fgPhone);
      if (this.fgPhone == "" || flag == false) {
        Toast.fail("请输入手机号码");
      } else {
        let res = await wxvcode(this.fgPhone, 5);
        if (res.data.status == "OK") {
          Toast.success(res.data.msg);
          const TIME_COUNT = 60;
          if (!this.forgetTimer) {
            this.forgetcodeTime = TIME_COUNT;
            this.forgetcodeFlag = true;
            this.forgetTimer = setInterval(() => {
              if (
                this.forgetcodeTime > 0 &&
                this.forgetcodeTime <= TIME_COUNT
              ) {
                this.forgetcodeTime--;
              } else {
                this.forgetcodeFlag = false;
                clearInterval(this.forgetTimer);
                this.forgetTimer = null;
              }
            }, 1000);
          }
        } else if (res.data.status == "isv.BUSINESS_LIMIT_CONTROL") {
          const TIME_COUNT = 60;
          if (!this.forgetTimer) {
            this.forgetcodeTime = TIME_COUNT;
            this.forgetcodeFlag = true;
            this.forgetTimer = setInterval(() => {
              if (
                this.forgetcodeTime > 0 &&
                this.forgetcodeTime <= TIME_COUNT
              ) {
                this.forgetcodeTime--;
              } else {
                this.forgetcodeFlag = false;
                clearInterval(this.forgetTimer);
                this.forgetTimer = null;
              }
            }, 1000);
          }
        } else {
          Toast.fail("发送验证码超过限制次数五次");
        }
      }
    },
    // 确认修改
    async onforgetSubmit(value) {
      let change = await appsChangePassword(
        value.fgPassword1,
        value.fgPhone,
        value.fgCode
      );
      console.log(change);
      if (change.data.status == 200) {
        Toast.success("修改成功");
        this.pwshow = false;
      } else {
        Toast.fail(change.data.msg);
      }
    },
    radioClick() {
      console.log(this.radio1);
      // if (i == "0") {
      //   this.radio = "1";
      // } else {
      //   this.radio = "0";
      // }
    },
  },
  created() {
    if (getCookie("re_username")) {
      let cookieName = getCookie("re_username");
      this.username = JSON.parse(cookieName).userName;
      this.password = JSON.parse(cookieName).passWord;
      this.radio1 = true;
    }
    let registerFlag = getStorage("registerFlag");
    console.log(registerFlag);
    if (registerFlag) {
      this.pshow = true;
    }
  },
  mounted() {
    //首次进入的原始高度
    this.originalHeight = document.documentElement.clientHeight;
    window.addEventListener("resize", this.watchResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.watchResize);
  },
  destroyed() {},
};
</script>
<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100vh;
  overflow-y: hidden;
  // background: #f0f2ff;

  background: #e5f3f3;
}
.title {
  width: 100%;
  margin: auto;
  padding: 0.6rem 0 0.5rem 0;
  & .t1 {
    margin: 0;
    font-size: 0.24rem;
    color: #2e2e2e;
  }
  & .t2 {
    margin-top: 0.2rem;
    font-size: 0.24rem;
    text-align: center;
    color: #5174da;
    // color: #2e2e2e;
  }
}
.title:before {
  content: "";
  display: block;
  width: 0.4rem;
  height: 0.4rem;
  border-radius: 50%;
  background: #fff6d9;
  position: absolute;
  top: 0.54rem;
  right: 0.3rem;
}
.field {
  position: relative;
  z-index: 10;
  width: 80%;
  // height: 2.2rem;
  background: rgba(255, 255, 255, 0.4);
  margin: 0 auto;
  // margin-top: 0.1rem;
  border-radius: 0.16rem;
  box-shadow: 0 10px 30px 0 rgba(73, 115, 215, 0.3);
  box-sizing: border-box;
  padding: 0.32rem 0.32rem 0.35rem 0.32rem;
  & .login-btn {
    margin-top: 0.1rem;
  }
  & .van-cell {
    font-size: 0.14rem;
    & /deep/ .van-field__label {
      margin-right: 0;
    }
  }
}
.login-img {
  width: 100%;
  position: absolute;
  bottom: -0.2rem;
  left: 0;
  z-index: 0;
  opacity: 0.8;
  & img {
    width: 100%;
    height: 100%;
  }
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.language {
  position: relative;
  color: #fff;
  width: 0.3rem;
  height: 0.3rem;
  float: right;
  margin: 0.15rem;
}
.language span {
  display: inline-block;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 2px;
  font-size: 12px;
}
.language .language__active,
.language .language__alt {
  position: absolute;
  -webkit-transition: all 0.35s ease-in-out;
  -moz-transition: all 0.35s ease-in-out;
  transition: all 0.35s ease-in-out;
}
.language .language__active {
  color: #1ecfe6;
  background-color: #fff;
  top: 0;
  left: 0;
  z-index: 1;
}
.language .language__alt {
  color: #fff;
  background-color: #303030;
  top: 10px;
  left: 13px;
  z-index: 0;
}
.forget {
  // display: inline-block;
  float: right;
  margin: 0;
  margin-top: 0.1rem;
  text-align: right;
  color: #999999;
  font-size: 0.12rem;
}
.new {
  // margin: 0 auto;
  float: left;
  text-align: left;
  color: #999999;
  margin-top: 0.1rem;
  font-size: 0.12rem;
}
.pshow {
  width: 90%;
  border-radius: 10px;
  background: #e5f3f3;
}
.field2 {
  position: relative;
  z-index: 10;
  // width: 95%;
  // height: 2.2rem;
  background: #e5f3f3;
  margin: 0 auto;
  margin-top: 0.4rem;
  margin-bottom: 0.3rem;
  border-radius: 0.16rem;
  // box-shadow: 0 10px 30px 0 rgba(73, 115, 215, 0.3);
  box-sizing: border-box;
  padding: 0.32rem 0.2rem 0.08rem 0.2rem;
  & .login-btn {
    margin: 0.2rem 0;
  }
  & .van-cell {
    font-size: 0.14rem;
    & /deep/ .van-field__label {
      margin-right: 0;
    }
  }
}
.xy {
  text-align: left;
  margin-top: 0.15rem;
  // margin-bottom: 0.2rem;
  display: flex;
  align-items: center;
  & .groups {
    // display: inline-block;
    & /deep/ .van-checkbox__icon {
      font-size: 0.14rem;
    }
    & /deep/ .van-checkbox__label {
      font-size: 0.12rem !important;
    }
  }
  & .text {
    margin-left: 0.05rem;
    display: inline-block;
    font-size: 0.14rem;
  }
}
.role-box {
  height: 100%;
  background: #e5f3f3;
  & .titles {
    font-size: 0.2rem;
    padding-top: 0.1rem;
  }
}
.role {
  display: flex;
  flex-direction: column;
  & div {
    flex: 1;
    margin: 0.1rem 0;
    & img {
      width: 1.3rem;
      height: 1.3rem;
    }
  }
}
.role-btn {
  position: fixed;
  bottom: 0.1rem;
  width: 95%;
  left: 50%;
  transform: translateX(-50%);
}
</style>